import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:xin_nuo_pda/http/api/user_api.dart';
import 'package:xin_nuo_pda/base/BaseController.dart';
import 'package:xin_nuo_pda/routes/Routes.dart';
import 'package:xin_nuo_pda/values/constant.dart';
import '../bean/version_entity.dart';
import '../generated/json/base/json_convert_content.dart';
import '../utils/permission_utils.dart';
import '../views/custom_dialog/get_widget_dialog_view.dart';
import '../views/custom_dialog/progress_dialog_view.dart';

class LoginController extends BaseController {
  TextEditingController name = TextEditingController();
  TextEditingController passWord = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    saveUpdateApp();
  }

  saveUpdateApp() async {
    printInfo(info: '更新App');
    List<Permission> permissions = [
      Permission.storage,
      Permission.requestInstallPackages
    ];
    PermissionUtils.check(permissions,
        onSuccess: () async {
          var info = await UserApi.checkUpdate(canelToken);
          Map<String, dynamic> responseData =  jsonDecode(info);
          VersionEntity? requestJson = JsonConvert.fromJsonAsT<VersionEntity>(responseData);
          String? s = requestJson.desc;
          int? c = requestJson.version?.compareTo(Get.find<PackageInfo>().version);
          if (c == 1) {
            Get.dialog(
                GetWidgetDialogWidget(
                  title: "发现新版本",
                  message: "更新内容\n" + s!,
                  confirmText: "立即更新",
                  onConfirmEvent: () {
                    Get.back();
                    downLoadApk(requestJson.downUrl);
                  },
                ),
                barrierDismissible: false);
          }
        },
        onFailed: () {},
        onOpenSetting: () {
          openAppSettings();
        });
  }

  void downLoadApk(String? resourceUrl) {
    Get.dialog(
        ProgressDialogWidget(
          title: "文件下载中",
          url: resourceUrl ?? "",
        ),
        barrierDismissible: false);
  }

  login() async {
    if (name.text.isEmpty) {
      Get.snackbar('提示', '请输入用户名');
      return;
    }
    if (passWord.text.isEmpty) {
      Get.snackbar('提示', '请输入密码');
      return;
    }
    Map<String, dynamic> params = {
      'ACTIONTYPE': 'LOGIN',
      'USERNAME': name.text,
      'PASSWORD': passWord.text
    };
    var result = await UserApi.login(canelToken, params: params);
    if (result.ok) {
      USER = result.data!.uSER.uSERNAME;
      authority();
    }
    // Get.offAllNamed(Routes.Tabs);
  }

  authority() async {
    Map<String, dynamic> params = {
      'NAME': name.text,
      'AUTHORITYCATEGORY': 'PDA'
    };
    var result = await UserApi.authority(params: params);
    result?.authoritylist.forEach((element) {
      print(element.labelzh);
      AUTHList.add(element.labelzh);
    });
    Get.snackbar('提示', '登录成功');
    Fluttertoast.showToast(
      msg: "登录成功",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
    );
    Get.offAllNamed(Routes.Tabs);
  }
}
